package com.xiaozhengkeji.springboot.speed.api.v1;



import com.xiaozhengkeji.springboot.speed.bean.ResponseBean;
import com.xiaozhengkeji.springboot.speed.pojo.UploadFilePoJo;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.authz.annotation.RequiresAuthentication;
import org.bson.types.Binary;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import java.io.IOException;
import java.util.*;

@Slf4j
@RestController
@RequestMapping("/v1/file")
public class FileApi {
    @Autowired
    private MongoTemplate mongoTemplate;


    @ApiOperation("文件上传接口-需要登陆")
    @PostMapping("/uploadfile")
    @RequiresAuthentication
    public ResponseBean uploadFile(@RequestParam("file") MultipartFile file) throws Exception {
        if (file.isEmpty()) {
            return new ResponseBean(200, "请选择文件", null);
        }
        String fileName = file.getOriginalFilename();
        ResponseBean responseBean = null;
        try {
            UploadFilePoJo uploadFile = new UploadFilePoJo();
            uploadFile.setName(fileName);
            uploadFile.setCreatedTime(new Date());
            uploadFile.setContent(new Binary(file.getBytes()));
            uploadFile.setContentType(file.getContentType());
            uploadFile.setSize(file.getSize());
            UploadFilePoJo savedFile = mongoTemplate.save(uploadFile);
            String url = savedFile.getId();
            responseBean = new ResponseBean(200, "上传成功", url);
        } catch (IOException e) {
            e.printStackTrace();
            responseBean = new ResponseBean(500, "上传失败", null);
        }
        return responseBean;
    }

    @ApiOperation("图床传输接口")
    @GetMapping("/imgs")
    public byte[] imgs(@RequestParam(name = "file_id") String fileId, HttpServletRequest request, HttpServletResponse response) throws Exception {
        byte[] data = null;
        UploadFilePoJo file = mongoTemplate.findById(fileId, UploadFilePoJo.class);
        if (file != null) {
            data = file.getContent().getData();
        }
        if(!file.getContentType().equalsIgnoreCase("image/jpeg")){
            return null;
        }
        String fileName = file.getName();
        if (request.getHeader("User-Agent").toUpperCase().contains("MSIE") ||
                request.getHeader("User-Agent").toUpperCase().contains("TRIDENT")
                || request.getHeader("User-Agent").toUpperCase().contains("EDGE")) {
            fileName = java.net.URLEncoder.encode(fileName, "UTF-8");
        } else {
            //非IE浏览器的处理：
            fileName = new String(fileName.getBytes("UTF-8"), "ISO-8859-1");
        }
        // 通知浏览器进行文件下载
        response.setContentType(file.getContentType());
        response.setHeader("Content-Disposition", "attachment;filename=\"" + fileName + "\"");
        return data;
    }

    @ApiOperation("文件下载接口-需要登陆")
    @GetMapping("/download")
    @RequiresAuthentication
    public byte[] download(@RequestParam(name = "file_id") String fileId, HttpServletRequest request, HttpServletResponse response) throws Exception {
        byte[] data = null;
        UploadFilePoJo file = mongoTemplate.findById(fileId, UploadFilePoJo.class);
        if (file != null) {
            data = file.getContent().getData();
        }
        String fileName = file.getName();
        if (request.getHeader("User-Agent").toUpperCase().contains("MSIE") ||
                request.getHeader("User-Agent").toUpperCase().contains("TRIDENT")
                || request.getHeader("User-Agent").toUpperCase().contains("EDGE")) {
            fileName = java.net.URLEncoder.encode(fileName, "UTF-8");
        } else {
            //非IE浏览器的处理：
            fileName = new String(fileName.getBytes("UTF-8"), "ISO-8859-1");
        }
        // 通知浏览器进行文件下载
        response.setContentType(file.getContentType());
        response.setHeader("Content-Disposition", "attachment;filename=\"" + fileName + "\"");
        return data;
    }
}
